import numpy as np

def loadDataSet():
    # 词条切分后的文档集合，来自斑点犬爱好者留言板。留言文本被切分为一系列的词条集合，去除标点符号
    postingList = [['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'],
                   ['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'],
                   ['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'him'],
                   ['stop', 'posting', 'stupid', 'worthless', 'garbage'],
                   ['mr', 'licks', 'ate', 'my', 'steak', 'how', 'to', 'stop', 'him'],
                   ['quit', 'buying', 'worthless', 'dog', 'food', 'stupid']]
    classVec = [0, 1, 0, 1, 0, 1] # 1代表侮辱性文字 0代表正常言论， 该数据由人工标注
    return postingList, classVec

# 使用dataSet中词汇创建不重复的词汇表
def createVocabList(dataSet):
    vocabSet = set([])
    for document in dataSet:
        vocabSet = vocabSet | set(document)  #创建两个集合的并集
    return list(vocabSet)

# 词集模型 set-of-words-model
# 为词汇表创建一个向量，长度和词汇表相同，元素值1代表该位置的词汇在输入文档inputSet中出现
def setOfWords2Vec(vocabList, inputSet):
    returnVec = [0]*len(vocabList) #创建一个所有元素都为0的向量
    for word in inputSet:
        if word in vocabList:
            returnVec[vocabList.index(word)] = 1
        else:
            print("the word: %s is not in my Vocabulary!" %word)
    return returnVec

# 词袋模型 bag-of-words-model
def bagOfWords2VecMN(vocabList, inputSet):
    returnVec = [0]*len(vocabList)
    for word in inputSet:
        if word in vocabList:
            returnVec[vocabList.index(word)] += 1
    return returnVec

# trainMatrix 为训练集中所有文档调用setOfWords2Vec的返回向量组成的矩阵，
#             向量意义为词汇表中的词汇是否在文档中出现
# trainCategory 为训练集中所有文档的类别标签列表
def trainNB0(trainMatrix, trainCategory):
    numTrainDocs = len(trainMatrix)
    numWords = len(trainMatrix[0]) #就是词汇表长度
    pAbusive = sum(trainCategory)/float(numTrainDocs) #任意文档属于侮辱性文档的概率 （将trainCategory列表中的所有1相加即为侮辱性文档数量）

    # 利用贝叶斯分类器对文档进行分类时，要计算多个概率的乘积以获得文档属于某个类别的概率，
    # 即计算p(w0|1)p(w1|1)p(w2|1)。如果其中一个概率值为0，那么最后的乘积也为0。
    # 为降低这种影响，可以将所有词的出现数初始化为1，并将分母初始化为2。这样当一个词没出现时，其概率是0.5。修正后概率的相对性不变

    p0Num = np.ones(numWords) #np.zeros(numWords) # 该向量记录出现在正常文档中的词汇的数量
    p1Num = np.ones(numWords) #np.zeros(numWords) # 该向量记录出现在侮辱性文档中的词汇的数量
    p0Denom = 2.0 #0.0
    p1Denom = 2.0 #0.0
    for i in range(numTrainDocs):
        if trainCategory[i] == 1: # 当前是侮辱性文档，即类别1
            p1Num += trainMatrix[i] #增加词汇在类别1中的计数值
            p1Denom += sum(trainMatrix[i]) #累加类别1文档中出现的词汇总数
        else:
            p0Num += trainMatrix[i]
            p0Denom += sum(trainMatrix[i])

    # 另一个遇到的问题是下溢出，这是由于太多很小的数相乘造成的。当计算乘积p(w0|ci)p(w1|ci)p(w2|ci)...p(wN|ci)时，
    # 由于大部分因子都非常小，所以程序会下溢出或者得到不正确的答案
    # 一种解决办法是对乘积取自然对数

    p1Vect = np.log(p1Num / p1Denom) # 计算每个词汇在类别1中出现的条件概率 P(wi|c1) = 所有类别1文档中词汇wi出现的次数/所有类别1文档的总词汇数
    p0Vect = np.log(p0Num / p0Denom)
    return p0Vect, p1Vect, pAbusive

def classifyNB(vec2Classify, p0Vec, p1Vec, pClass1):
    p1 = sum(vec2Classify * p1Vec) + np.log(pClass1)      #元素相乘
    p0 = sum(vec2Classify * p0Vec) + np.log(1.0 - pClass1)
    if p1 > p0:
        return 1
    else:
        return 0
    
def testingNB():
    listOPosts, listClasses = loadDataSet()
    myVocabList = createVocabList(listOPosts)
    trainMat = []
    for postinDoc in listOPosts:
        trainMat.append(setOfWords2Vec(myVocabList, postinDoc))
    p0V, p1V, pAb = trainNB0(np.array(trainMat), np.array(listClasses))
    
    testEntry = ['love', 'my', 'dalmation']
    thisDoc = np.array(setOfWords2Vec(myVocabList, testEntry))
    print(testEntry, 'classified as:', classifyNB(thisDoc, p0V, p1V, pAb))

    testEntry = ['stupid', 'garbage']
    thisDoc = np.array(setOfWords2Vec(myVocabList, testEntry))
    print(testEntry, 'classified as:', classifyNB(thisDoc, p0V, p1V, pAb))

def textParse(bigString): #input is big string, output is word list
    import re
    listOfTokens = re.split(r'\W+', bigString)
    return [tok.lower() for tok in listOfTokens if len(tok) > 2]

# 垃圾邮件分类测试
def spamTest():
    docList = []; classList = []; fullText = []
    for i in range(1, 26): #数据集，两类邮件各25封
        wordList = textParse(open('email/spam/%d.txt' %i, encoding="ISO-8859-1").read())
        docList.append(wordList)
        fullText.append(wordList)
        classList.append(1)
        wordList = textParse(open('email/ham/%d.txt' % i, encoding="ISO-8859-1").read())
        docList.append(wordList)
        fullText.extend(wordList)
        classList.append(0)
    vocabList = createVocabList(docList) #创建词汇表
    trainingSet = list(range(50)); #初始索引序列[0,50)
    testSet = [] #创建测试集
    #随机从训练集中取10个作为测试集
    for i in range(10):
        randIndex = int(np.random.uniform(0, len(trainingSet)))
        testSet.append(trainingSet[randIndex])
        del(trainingSet[randIndex])
    trainMat = []; trainClasses = []
    for docIndex in trainingSet: #train the classifier (get probs) trainNB0
        trainMat.append(bagOfWords2VecMN(vocabList, docList[docIndex]))
        trainClasses.append(classList[docIndex])
    p0V, p1V, pSpam = trainNB0(np.array(trainMat), np.array(trainClasses))
    errorCount = 0
    for docIndex in testSet: #classify the remaining items
        wordVector = bagOfWords2VecMN(vocabList, docList[docIndex])
        if classifyNB(np.array(wordVector), p0V, p1V, pSpam) != classList[docIndex]:
            errorCount += 1
            print("classification error", docList[docIndex], "real class is", classList[docIndex])
    print('the error rate is: ', float(errorCount)/len(testSet))

# rss 分析
def calcMostFreq(vocabList, fullText):
    import operator
    freqDict = {}
    for token in vocabList:
        freqDict[token] = fullText.count(token)
    sortedFreq = sorted(freqDict.items(), key=operator.itemgetter(1), reverse=True)
    return sortedFreq[:30]

def localWords(feed1, feed0):    
    docList = []; classList = []; fullText = []
    minLen = min(len(feed1['entries']), len(feed0['entries']))
    print('min len is ', minLen)
    for i in range(minLen):
        wordList = textParse(feed1['entries'][i]['summary'])
        docList.append(wordList)
        fullText.extend(wordList)
        classList.append(1) #feed1 is class 1
        wordList = textParse(feed0['entries'][i]['summary'])
        docList.append(wordList)
        fullText.extend(wordList)
        classList.append(0)
    vocabList = createVocabList(docList)#create vocabulary
    #print(vocabList)
    top30Words = calcMostFreq(vocabList, fullText)   #remove top 30 words
    print(top30Words)
    for pairW in top30Words:
        if pairW[0] in vocabList: vocabList.remove(pairW[0])
    trainingSet = list(range(2*minLen)); testSet = []           #create test set
    for i in range(20):
        randIndex = int(np.random.uniform(0, len(trainingSet)))
        testSet.append(trainingSet[randIndex])
        del(trainingSet[randIndex])
    trainMat = []; trainClasses = []
    for docIndex in trainingSet:#train the classifier (get probs) trainNB0
        trainMat.append(bagOfWords2VecMN(vocabList, docList[docIndex]))
        trainClasses.append(classList[docIndex])
    p0V, p1V, pSpam = trainNB0(np.array(trainMat), np.array(trainClasses))
    errorCount = 0
    for docIndex in testSet:        #classify the remaining items
        wordVector = bagOfWords2VecMN(vocabList, docList[docIndex])
        if classifyNB(np.array(wordVector), p0V, p1V, pSpam) != classList[docIndex]:
            errorCount += 1
    print('the error rate is: ', float(errorCount)/len(testSet))
    return vocabList, p0V, p1V

def getTopWords(feed1, feed0):
    import operator
    vocabList, p0V, p1V = localWords(feed1, feed0)
    topFeed1 = []; topFeed0 = []
    print('p0V',p0V,' len ',len(p0V))
    for i in range(len(p0V)):
        if p0V[i] > -6.0: topFeed0.append((vocabList[i], p0V[i]))
        if p1V[i] > -6.0: topFeed1.append((vocabList[i], p1V[i]))
    sortedFeed0 = sorted(topFeed0, key=lambda pair: pair[1], reverse=True)
    print("Feed0 =============================================")
    print('sortedFeed0 len ',len(sortedFeed0))
    #for item in sortedSF:
    #    print(item[0])
    sortedFeed1 = sorted(topFeed1, key=lambda pair: pair[1], reverse=True)    
    print("Feed1 ==============================================")
    print('sortedFeed1 len ',len(sortedFeed1))
    #for item in sortedNY:
    #    print(item[0])

def rssTest():
    feed1Rss = 'https://plink.anyfeeder.com/people'
    feed0Rss = 'https://plink.anyfeeder.com/weibo/search/hot'
    import feedparser
    feed1 = feedparser.parse(feed1Rss)
    feed0 = feedparser.parse(feed0Rss)
    # localWords(feed1, feed0)
    # localWords(feed1, feed0)
    # localWords(feed1, feed0)
    # localWords(feed1, feed0)
    # localWords(feed1, feed0)
    getTopWords(feed1, feed0)



    